package com.telit.firecommand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.telit.common.util.TimeUtils;
import com.telit.firecommand.entity.DailyWeather;
import com.telit.firecommand.entity.HourlyWeather;
import com.telit.firecommand.entity.NowWeather;
import com.telit.firecommand.entity.WeatherResults;
import com.telit.firecommand.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Auther amy
 * @Describe 天气实现层
 */
@Service
public class WeatherServiceImpl implements WeatherService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${weather.url}")
    private String WEATHER_URL;

    @Value("${weather.key}")
    private String key;

    @Override
    public NowWeather getNowWeather(String location) {
        Map<String,Object> paramsMap = new HashMap<>(4);
        paramsMap.put("key",key);
        paramsMap.put("location",location);
        String result = restTemplate.getForObject(WEATHER_URL + "v3/weather/now.json?key={key}&location={location}&language=zh-Hans&unit=c",String.class, paramsMap);
        JSONObject resultJson = JSON.parseObject(result,JSONObject.class);
        List<WeatherResults> jsonObject = JSON.parseArray(JSON.toJSONString(resultJson.get("results")),WeatherResults.class);
        NowWeather nowWeather=JSON.parseObject(JSON.toJSONString(jsonObject.get(0).getNow()),NowWeather.class);
        nowWeather.setLast_update(TimeUtils.convertStandtardTime2(jsonObject.get(0).getLast_update()));
//        return JSON.parseObject(JSON.toJSONString(jsonObject.get(0).getNow()),NowWeather.class);
        return nowWeather;
    }

    @Override
    public String getDailyWeatherString(String location,Integer start,Integer day) {
        Map<String,Object> paramsMap = new HashMap<>(4);
        paramsMap.put("key",key);
        paramsMap.put("location",location);
        paramsMap.put("start",start);
        paramsMap.put("day",day);
        String result = restTemplate.getForObject(WEATHER_URL + "v3/weather/daily.json?key={key}&location={location}&language=zh-Hans&unit=c&start={start}&day={day}",String.class, paramsMap);
        return result;
    }

    @Override
    public DailyWeather getOneDayWeather(String location, Integer start, Integer day) {
        String result = getDailyWeatherString(location, start, day);
        JSONObject resultJson = JSON.parseObject(result, JSONObject.class);
        List<WeatherResults> jsonObject = JSON.parseArray(JSON.toJSONString(resultJson.get("results")),
                WeatherResults.class);
        List<DailyWeather> list = jsonObject.get(0).getDaily();
        return list == null ? null : list.get(0);
    }


    /**
     * 获取时间周期的天气
     */
    @Override
    public List<DailyWeather> getWeather(String location, Integer start, Integer day) {
        String result = getDailyWeatherString(location, start, day);
        JSONObject resultJson = JSON.parseObject(result, JSONObject.class);
        List<WeatherResults> jsonObject = JSON.parseArray(JSON.toJSONString(resultJson.get("results")),
                WeatherResults.class);
        return jsonObject.get(0).getDaily();
    }

    @Override
    public Double getSpreadRate(NowWeather nowWeather) {
        if (nowWeather != null) {
            // 计算蔓延速度 R0 = aT + bV + ch - D  单位是米/分钟 风速需要是米/秒
            // a= 0.03 b= 0.05 c = 0.01 D = 0.3
            Double temperature = Double.valueOf(nowWeather.getTemperature());
            Double windSpeed = Double.valueOf(nowWeather.getWind_speed());
            Double humidity = 100 - Double.valueOf(nowWeather.getHumidity());
            Double spreadRate = 0.03 * temperature + 0.05 * windSpeed + 0.01 * humidity - 0.3;
            // 保留两位小数
            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(2);
            return new Double(nf.format(new BigDecimal(spreadRate)));
        }
        return null;
    }

    @Override
//    @Cacheable(value = "firecommand:weather:getHourlyWeather", depict = "根据地址查询24小时的天气信息",
//            firstCache = @FirstCache(expireTime = 12, timeUnit = TimeUnit.HOURS),
//            secondaryCache = @SecondaryCache(expireTime = 18, preloadTime = 2, forceRefresh = true, timeUnit = TimeUnit.HOURS))
    public List<HourlyWeather> getHourlyWeather(String location) {
        Map<String,Object> paramsMap = new HashMap<>(4);
        paramsMap.put("key",key);
        paramsMap.put("location",location);
        String result = restTemplate.getForObject(WEATHER_URL + "v3/weather/hourly.json?key={key}&location={location}&language=zh-Hans&unit=c&start=0&hours=24",String.class, paramsMap);
        JSONObject resultJson = JSON.parseObject(result,JSONObject.class);
        List<WeatherResults> jsonObject = JSON.parseArray(JSON.toJSONString(resultJson.get("results")),WeatherResults.class);
        List<HourlyWeather> hourlyList = jsonObject.get(0).getHourly();
        // 计算风力
        if(!CollectionUtils.isEmpty(hourlyList)){
            hourlyList.forEach(hourly -> hourly.setWind_scale(getWindScale(new BigDecimal(hourly.getWind_speed()))));
        }
        return hourlyList;
    }

    /**
     * 获取风力等级，风速单位km/h
     */
    private String getWindScale(BigDecimal windSpeed) {
        String windScale = null;
        if (windSpeed.compareTo(new BigDecimal("1")) < 0) {
            windScale = "0";
        } else if (windSpeed.compareTo(new BigDecimal("5")) <= 0) {
            windScale = "1";
        } else if (windSpeed.compareTo(new BigDecimal("11")) <= 0) {
            windScale = "2";
        } else if (windSpeed.compareTo(new BigDecimal("19")) <= 0) {
            windScale = "3";
        } else if (windSpeed.compareTo(new BigDecimal("28")) <= 0) {
            windScale = "4";
        } else if (windSpeed.compareTo(new BigDecimal("38")) <= 0) {
            windScale = "5";
        } else if (windSpeed.compareTo(new BigDecimal("49")) <= 0) {
            windScale = "6";
        } else if (windSpeed.compareTo(new BigDecimal("61")) <= 0) {
            windScale = "7";
        } else if (windSpeed.compareTo(new BigDecimal("74")) <= 0) {
            windScale = "8";
        } else if (windSpeed.compareTo(new BigDecimal("88")) <= 0) {
            windScale = "9";
        } else if (windSpeed.compareTo(new BigDecimal("102")) <= 0) {
            windScale = "10";
        } else if (windSpeed.compareTo(new BigDecimal("117")) <= 0) {
            windScale = "11";
        } else if (windSpeed.compareTo(new BigDecimal("133")) <= 0) {
            windScale = "12";
        } else if (windSpeed.compareTo(new BigDecimal("149")) <= 0) {
            windScale = "13";
        } else if (windSpeed.compareTo(new BigDecimal("166")) <= 0) {
            windScale = "14";
        } else if (windSpeed.compareTo(new BigDecimal("183")) <= 0) {
            windScale = "15";
        } else if (windSpeed.compareTo(new BigDecimal("201")) <= 0) {
            windScale = "16";
        } else if (windSpeed.compareTo(new BigDecimal("220")) <= 0) {
            windScale = "17";
        }
        return windScale;
    }
}
